from xml.etree import ElementTree as ET

def xml():
    parser = ET.parse("file")
    root = parser.getroot()
    root = ET.fromstring("<xml/>")
    root.tag
    root.attrib
    root.text
    for img in root.findall("./DESC/DESC[[@Name='Version']"):pass
    for xml_cp in root.findall('./target/filecopy/xml_cp'):
        path = xml_cp.attrib["path"]

def make_xml(xml):

    root = ET.Element( 'root' )
    brd = ET.Element('BRD')
    brd.attrib["name"] = brd_name
    etsig.text = _sign["@signfile"]
    root.append(brd)
    parser = ET.ElementTree(root)
    parser.write("pkg2.xml", xml_declaration=True, encoding='utf-8')
    ident_xml("pkg2.xml", "pkg2.xml")


# 格式化xml
from xml.dom import minidom
def ident_xml(src_xml, des_xml, indent="\t", newl="\n", encoding="utf-8"):
    with open(src_xml) as fp:
        xml_text = fp.read()
    dom = minidom.parseString(xml_text)
    with open(des_xml, 'w', newline=newl) as f:
        dom.writexml(f, "", indent, newl, encoding)


def pretty_xml(element, indent="    ", newline="\n", level=0):
    """
    xml 格式美化
    :param element: elemnt为传进来的Elment类
    :param indent: 参数indent用于缩进
    :param newline: newline用于换行
    :param level:
    :return:
    """
    if element:  # 判断element是否有子元素
        if (element.text is None) or element.text.isspace():  # 如果element的text没有内容
            element.text = newline + indent * (level + 1)
        else:
            element.text = newline + indent * (level + 1) + element.text.strip() + newline + indent * (level + 1)
    temp = list(element)  # 将element转成list
    for subelement in temp:
        if temp.index(subelement) < (len(temp) - 1):  # 如果不是list的最后一个元素，说明下一个行是同级别元素的起始，缩进应一致
            subelement.tail = newline + indent * (level + 1)
        else:  # 如果是list的最后一个元素， 说明下一行是母元素的结束，缩进应该少一个
            subelement.tail = newline + indent * level
        pretty_xml(subelement, indent, newline, level=level + 1)  # 对子元素进行递归操作

        
